package myclient;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JOptionPane;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
/**
 * @author JIAO
 */
public class MyTreeSelectionListener implements TreeSelectionListener,MouseListener,ActionListener{
	static TreePath path =null;
	MainFrame frame;
	MyTreeSelectionListener(MainFrame frame){
		this.frame = frame;
	}
	public void valueChanged(TreeSelectionEvent e) {
		path = e.getNewLeadSelectionPath();
	}
	public void mouseClicked(MouseEvent e) {
		TreeNode node = null;
		
		
		if(e.getButton()==3){//鼠标右击
			if(path==null){
				JOptionPane.showMessageDialog(frame.panel,"请先单击选择一个好友！" );
				return;
			}
			frame.popupMenu.show(frame.panel, e.getX(), e.getY());
		}
		if(e.getClickCount()==2){
			if(path==null)
				return;
			node = (TreeNode)path.getLastPathComponent();
			if(!node.isLeaf()){
				path = null;
				return;
			}
			makeTalkFrame(node.toString());
		}
		
	}
	public void mouseEntered(MouseEvent e) {
	}
	public void mouseExited(MouseEvent e) {
	}
	public void mousePressed(MouseEvent e) {
	}
	public void mouseReleased(MouseEvent e) {
	}
	public void actionPerformed(ActionEvent e) {
		if(path==null)
			return;
		TreeNode node = (TreeNode)path.getLastPathComponent();
		if(e.getActionCommand().equals("发送即时消息")){
			System.out.println("发送即时消息");
			makeTalkFrame(node.toString());
		}else if(e.getActionCommand().equals("删除好友")){
			System.out.println("删除好友");
			frame.conn.writer.println("server");
			frame.conn.writer.println("deleteFriend");
			frame.conn.writer.println(node.toString());
		}else if(e.getActionCommand().equals("将好友移动到")){
			System.out.println("将好友移动到");
		}else if(e.getActionCommand().equals("查看资料")){
			System.out.println("查看资料");
			
		}
		
	}
	
	public void makeTalkFrame(String sID){
		if(frame.talkMap.containsKey(sID))//如果会话窗口已经打开，则返回
			return;
		TalkFrame talk = new TalkFrame(sID,frame);
		frame.talkMap.put(sID, talk);
		if(frame.haveMsgMap.containsKey(sID)){
			talk.area1.append(frame.haveMsgMap.get(sID));
			frame.haveMsgMap.remove(sID);
			if(frame.haveMsgMap.size()==0)
				frame.t.stop();			
		}
	}
	
}
